﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using TSL_Tools.SqlTools;
using ReportingEngine;
using System.IO;
using System.Windows.Controls.Primitives;

namespace VSLT_Reporting
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// This method searches the datagrid and finds the highlighted run(s). It then
        /// updates various settings based on the runs and the configuration of the app.
        /// It is called from both the "Get Runs" button and the "SelectionChanged" event
        /// handler.
        /// </summary>
        private void DataGridSelectionChanged()
        {
            selectedRuns.Clear();
            bool clearAllButtons = false;
            int x = 0;
            foreach (object obj in dgMainResults.SelectedItems)
            {
                DataRowView row = (DataRowView)obj;
                if(row["ParsingFailed"].ToString().ToLower() == "false")
                { 
                    int _runId;
                    Int32.TryParse(row[0].ToString(), out _runId);
                    selectedRuns.Add(_runId);
                }
            }
            if(selectedRuns.Count == 0)
            {
                // Did not find a valid run.
                MessageBox.Show("It appears as though you selected a run that was not parsed properly. Please select a different run to get results.","Attention");
                ClearReportTab();
                clearAllButtons = true;
            }
            selectedRuns.Sort();
            x = UpdateActiveButtons(clearAllButtons);
            if (x != -1)
            {
                currentlyHighlightedRunId = x;
                GetRunInfoForHighlightedRun(x);
                ObjectValidationPropertyGrid.SelectedObject = re.listOfRuns[x];
            }

        }

        private void PopulateDataGridWithRuns()
        {
            System.Windows.Input.Cursor _cursor = this.Cursor;
            this.Cursor = Cursors.Wait;

            string sqlConn = Properties.Settings.Default.sqlConn;
            string sqlCmd = TSL_ReportingEngine.Sql_GETRUNSFORDATAGRID;
            DataTable _table;
            TimeSpan ts = tts.ExecuteReaderTable(sqlCmd, out _table);
            AddDebugTimingInfo(ts, "--PopulateDataGridWithRuns  " + sqlCmd);
            mostRecentSqlQuery = sqlCmd;
            dgMainResults.ItemsSource = _table.AsDataView();
            tsslMessage.Content = String.Format(Msg_NUMBEROFRESULTSLOADED, _table.Rows.Count);
            re.GetAllCoreLoadTestInfo();
            ClearReportTab();
            tabMainResults.IsSelected = true;
            this.Cursor = _cursor;
        }

        // ADDED TO REPORTING_GENERATOR
        private void GetLoadTestInfoForHighlightedRun(int runId, bool appendTheInfo)
        {
            string finalText = "";
            using (StreamReader sr = new StreamReader(Properties.Settings.Default.LoadTestPropertiesTemplateLocation))
            {
                string str = sr.ReadToEnd();
                finalText = AddRunSettings(str, runId);
            }

            using (StreamReader sr = new StreamReader(Properties.Settings.Default.ScenarioTemplateLocation))
            {
                string str = sr.ReadToEnd();
                finalText += AddScenarios(str, runId);
            }

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            MemoryStream ms = new MemoryStream(encoding.GetBytes(finalText));

            if (appendTheInfo)
            {
                TextRange text = new TextRange(rtbResults.Document.ContentEnd, rtbResults.Document.ContentEnd);
                text.Load(ms, DataFormats.Xaml);
            }
            else
            {
                TextRange text = new TextRange(rtbResults.Document.ContentStart, rtbResults.Document.ContentEnd);
                text.Load(ms, DataFormats.Xaml);
            }
        }

        // ADDED TO REPORTING_GENERATOR
        private string AddRunSettings(string sIn, int runId)
        {
            string sBody = sIn.Substring(0, sIn.Length - ("</Section>").Length);

            Dictionary<string, string> _dict = re.listOfRuns[runId].runConfiguration;
            foreach (KeyValuePair<string, string> kvp in _dict)
            {
                sBody = sBody.Replace("{{" + kvp.Key + "}}", kvp.Value);
            }
            
            return sBody;
        }

        // ADDED TO REPORTING_GENERATOR
        private string AddScenarios(string sIn, int runId)
        {
            // This part separates the template so that we have only one header and footer regardless of
            // how many times we add the template to the main string
            int iLen = sIn.IndexOf(">");
            string sHeader = sIn.Substring(0, iLen + 1);
            string sBody = sIn.Substring(iLen + 1);
            sBody = sBody.Substring(0, sBody.Length - ("</Section>").Length);

            StringBuilder sb = new StringBuilder();

            for (int iScenarioCount = 1; iScenarioCount <= re.listOfRuns[runId].scenarios.Count; iScenarioCount++)
            {
                Dictionary<string, string> _dict = re.listOfRuns[runId].scenarios.ElementAt(iScenarioCount - 1).Value;

                sb.Append(sBody);

                sb = sb.Replace("{{ScenarioName}}", _dict.ElementAt(0).Value);

                int numDictionaryItems = _dict.Count - 1;
                for (int x = 1; x < numDictionaryItems; x++)  // Get everything but the name and the test mix
                {
                    string sTemp = _dict.ElementAt(x).Value.Replace("\"", "");
                    sb = sb.Replace("{{" + _dict.ElementAt(x).Key + "}}", sTemp);
                }

                string str = _dict.ElementAt(numDictionaryItems).Value;
                int a = 1;

                foreach (string substr in str.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    sb = sb.Replace("{{TestCase}}" + a.ToString() + "a", substr);
                    a++;
                }

                while (a < 13)
                {
                    sb = sb.Replace("{{TestCase}}" + a.ToString() + "a", "");
                    a++;
                }
            }
            //runListInputStringForSqlQuery.Insert(0, sHeader);
            sb.Append("</Section>");
            return sb.ToString();
        }

        void dataGrid_LoadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e)
        {
            // Get the DataRow corresponding to the DataGridRow that is loading.
            DataRowView item = e.Row.Item as DataRowView;
            if (item != null)
            {
                if(item["ParsingFailed"].ToString().ToLower() != "true")
                {
                    e.Row.Background = new SolidColorBrush(Colors.White);
                }
                else
                {
                    e.Row.Background = new SolidColorBrush(Colors.LightSalmon);
                    e.Row.IsEnabled = false;
                }
                    //DataRow row = item.Row;

                // Access cell values values if needed...
                // var colValue = row["ColumnName1]";
                // var colValue2 = row["ColumName2]";

                // Set the background color of the DataGrid row based on whatever data you like from 
                // the row.


                //{
                //    MessageBox.Show("The Reporting Engine failed to parse one or more test runs. Please check the last column " +
                //        "of the 'List of Runs' datagrid to see which run(s) failed to parse.", "Information.");
                //    return;
                //}
            }
        }

    }
}



